package com.boat.starter.p6spy.logging;

import com.boat.starter.p6spy.context.Context;
import com.boat.starter.p6spy.logging.impl.MultilineSqlFormatter;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
/**
 * p6spy打印日志输出格式修改 
 * 
 * 1.只打印最终执行的sql. 
 * 2.sql换到下一行 
 * 3.结尾处增加分号,以标示sql结尾
 * 4.sql美化
 * 
 * @author 周江
 *
 */
public class LogFormat implements MessageFormattingStrategy {
	private SqlFormatter sqlFormatter = new MultilineSqlFormatter();

	@Override
	public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared,
			String sql, String url) {
		StringBuffer buffer = new StringBuffer();
		if (!("").equals(sql.trim())) {
			buffer.append("sql跟踪。");
			buffer.append("times: ").append(elapsed).append("ms , ");
			buffer.append("rowCount: ").append(Context.getSqlLogInfo().getRowCount()).append(" , ");
			buffer.append("connectionId: connection").append(connectionId).append("\n");
			buffer.append(beautifySql(sql)).append(";");
			return buffer.toString();
		}
		return "";
	}

	/**
	 * 美化Sql
	 */
	private String beautifySql(String sql) {
		return sqlFormatter.format(sql);
	}
}